package com.atguigu.gulimall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.common.utils.HttpUtils;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.common.vo.SocialUser;
import com.atguigu.common.vo.UserLoginVo;
import com.atguigu.common.vo.UserRegisterVo;
import com.atguigu.gulimall.member.dao.UserDao;
import com.atguigu.gulimall.member.dao.UserLevelDao;
import com.atguigu.gulimall.member.entity.UserEntity;
import com.atguigu.gulimall.member.entity.UserLevelEntity;
import com.atguigu.gulimall.member.exception.PhoneExistException;
import com.atguigu.gulimall.member.exception.UsernameExistException;
import com.atguigu.gulimall.member.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;


@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserDao, UserEntity> implements UserService {

    @Resource
    private UserLevelDao userLevelDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<UserEntity> page = this.page(
                new Query<UserEntity>().getPage(params),
                new QueryWrapper<UserEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void register(UserRegisterVo userRegisterVo) {
        UserEntity userEntity = new UserEntity();
        // 设置默认等级
        UserLevelEntity levelEntity =  userLevelDao.getDefaultLevel();
        userEntity.setLevelId(levelEntity.getId());
        // 检查用户名和手机号的唯一性，为了让controller能感知异常，使用异常机制
        this.checkPhoneUnique(userRegisterVo.getPhone());
        this.checkUsernameUnique(userRegisterVo.getUsername());

        userEntity.setPhone(userRegisterVo.getPhone());
        userEntity.setUsername(userRegisterVo.getUsername());
        userEntity.setNickname(userRegisterVo.getUsername());
        /**
         * 密码要进行加密存储
         * MD5不能直接进行密码的加密存储
         * MD5盐值加密，随机值
         */
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encode = passwordEncoder.encode(userRegisterVo.getPassword());
        userEntity.setPassword(encode);

        this.baseMapper.insert(userEntity);
    }

    @Override
    public void checkPhoneUnique(String phone) throws PhoneExistException {
        Integer count = this.baseMapper.selectCount(new QueryWrapper<UserEntity>().eq("phone", phone));
        if (count > 0) {
            throw new PhoneExistException();
        }
    }

    @Override
    public void checkUsernameUnique(String username) throws UsernameExistException {
        Integer count = this.baseMapper.selectCount(new QueryWrapper<UserEntity>().eq("username", username));
        if (count > 0) {
            throw new UsernameExistException();
        }
    }

    @Override
    public UserEntity login(UserLoginVo userLoginVo) {
        String loginacct = userLoginVo.getLoginacct();
        String password = userLoginVo.getPassword();
        // 去数据库查询
        UserEntity userEntity = this.baseMapper.selectOne(new QueryWrapper<UserEntity>().eq("username", loginacct).or().eq("phone", loginacct));
        if (userEntity == null) {
            // 登录失败
            return null;
        } else {
            String dbPassword = userEntity.getPassword();
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            // 密码匹配
            boolean result = encoder.matches(password, dbPassword);
            if (result) {
                return userEntity;
            } else {
                return null;
            }
        }
    }

    @Override
    public UserEntity login(SocialUser socialUser) throws Exception {
        // 登录和注册合并逻辑
        String uid = socialUser.getUid();
        // 判断当前社交用户是否已经登录过系统
        UserEntity entity = this.baseMapper.selectOne(new QueryWrapper<UserEntity>().eq("uid", uid));
        if (entity != null) {
            // 该用户已经注册
            UserEntity update = new UserEntity();
            update.setId(entity.getId());
            update.setAccessToken(socialUser.getAccess_token());
            update.setExpiresIn(socialUser.getExpires_in());
            this.baseMapper.updateById(update);

            entity.setAccessToken(socialUser.getAccess_token());
            entity.setExpiresIn(socialUser.getExpires_in());
            return entity;
        } else {
            // 没有查到当前社交用户对应的记录，需要注册一个
            UserEntity register = new UserEntity();
            try {
                // 查询当前社交用户的社交账号信息(昵称、性别等)
                Map<String, String> query = new HashMap<>();
                query.put("access_token", socialUser.getAccess_token());
                query.put("uid", socialUser.getUid());
                HttpResponse response = HttpUtils.doGet("https://api.weibo.com", "/2/users/show.json", "get", new HashMap<String, String>(), query);
                if (response.getStatusLine().getStatusCode() == 200) {
                    String json = EntityUtils.toString(response.getEntity());
                    JSONObject jsonObject = JSON.parseObject(json);
                    // 昵称
                    String name = jsonObject.getString("name");
                    String gender = jsonObject.getString("gender");
                    // ......其他信息
                    register.setNickname(name);
                    register.setGender("m".equals(gender) ? 1 : 0);
                }
            } catch (Exception e) {

            }

            register.setUid(socialUser.getUid());
            register.setAccessToken(socialUser.getAccess_token());
            register.setExpiresIn(socialUser.getExpires_in());
            this.baseMapper.insert(register);

            return register;
        }
    }

}